<template>

  <main role="main">


    <div class="album py-5 bg-light">

      <div class="container" >

        <div >
          <el-row>
            <el-col :span="5">
              <el-button size="large" round type="primary" @click="foldSwitchStatus = !foldSwitchStatus">
                <span v-show="foldSwitchStatus">▲收起试题分类</span>
                <span v-show="!foldSwitchStatus">▼展开试题分类</span>
              </el-button>
            </el-col>
            <el-col :span="5">
              <el-button size="large" round type="primary" color="#626aef" @click="categoryDialogVisible = true">
                试题分类管理
              </el-button>
            </el-col>
<!--            <el-col :span="5">-->
<!--              &lt;!&ndash;上传&ndash;&gt;-->
<!--              <el-upload-->
<!--                  action=""-->
<!--                  :multiple="false"-->
<!--                  :show-file-list="false"-->
<!--                  accept=".txt"-->
<!--                  :http-request="problemDescriptionFileParse"-->
<!--                  :file-list="problemDescriptionFile">-->
<!--                <el-button size="large" round type="warning">上传试题描述文件</el-button>-->
<!--              </el-upload>-->
<!--            </el-col>-->
<!--            <el-col :span="9">-->
<!--              <el-row>-->
<!--                <span style="text-align: -moz-center">解析试题描述文件 (<a href="../assets/problemDescription.txt" download="problemDescription.txt">下载试题描述文件模板</a>)</span>-->
<!--              </el-row>-->
<!--            </el-col>-->
          </el-row>
          <br>
          <transition name="problemDetailDraw">
            <div class="fold-switch"  v-show="foldSwitchStatus" style="display: flex;flex-wrap:wrap;">
              <div v-for="(levelOne, index) in problemCategories" :key="index" style="cursor: pointer;">
                <div class="row col-lg-12">
<!--                  <el-badge :value=levelOne.categoryLevelTwo.length type="warning">-->
<!--                                        <span :class="activeItem.includes(levelOne.parentCategory.problemCategorySlug)?'active':'Classification'" @click="onCheck(levelOne.parentCategory.problemCategorySlug, '')">-->
<!--                                            {{levelOne.parentCategory.problemCategoryName}}-->
<!--                                        </span>-->
<!--                  </el-badge>-->
<!--                  <div v-for="(levelTwo, index) in levelOne.categoryLevelTwo" :key="index">-->
<!--                    <span :class="activeItem.includes(levelTwo.problemCategorySlug)?'active':'Classification'" @click="onCheck(levelTwo.problemCategorySlug, levelOne.parentCategory.problemCategorySlug)">{{levelTwo.problemCategoryName}}</span>-->
<!--                  </div>-->
                  <span style="text-align: center;width: 120px" :class="activeItem.includes(levelOne.problemCategorySlug)?'active':'Classification'" @click="onCheck(levelOne.problemCategorySlug)">{{levelOne.problemCategoryName}}</span>

                </div>

              </div>
            </div>
          </transition>


          <br>


          <div class="form-group">
            <label for="time-limit">已选试题分类</label>
            <input type="text" class="form-control" id="category-selected" placeholder="" v-model="selectedCategory" disabled>
          </div>
          <div class="form-group">

            <el-row>

              <el-col :span="6">
                <label>试题标签</label>
                <select class="form-control" id="problem-tag" v-model="problem.problemTags">
                  <option>easy</option>
                  <option>medium</option>
                  <option>difficult</option>
                  <option>ultra</option>
                </select>
              </el-col>

              <el-col :span="6">
                <label>公开试题</label>
                <select class="form-control" id="problem-is-public" v-model="problem.isPublic">
                  <option>公开</option>
                  <option>私有</option>
                </select>
              </el-col>

              <el-col :span="6">
                <label>精确匹配</label>
                <select class="form-control" id="problem-is-exactly-match" v-model="problem.exactlyMatch">
                  <option>No</option>
                  <option>Yes</option>
                </select>
              </el-col>


            </el-row>
          </div>


          <div class="form-group" style="margin-top: 20px">
            <label for="problem-name">试题名称</label>
            <input type="text" class="form-control" id="problem-name" placeholder="" v-model="problem.problemName">
          </div>


          <div class="form-group">
            <label for="problem-name">试题语言</label>
            <div style="display: flex">
              <el-checkbox v-model="C" @change="addLanguage(C,1)" label="C" border></el-checkbox>
              <el-checkbox v-model="CPlus" @change="addLanguage(CPlus,2)"  label="C++" border></el-checkbox>
              <el-checkbox v-model="JAVA" @change="addLanguage(JAVA,3)"  label="Java" border></el-checkbox>
              <el-checkbox v-model="PASCAL" @change="addLanguage(PASCAL,4)"  label="Pascal" border></el-checkbox>
              <el-checkbox v-model="PYTHON" @change="addLanguage(PYTHON,5)"  label="Python" border></el-checkbox>
              <el-checkbox v-model="RUBY" @change="addLanguage(RUBY,6)"  label="Ruby" border></el-checkbox>
            </div>

<!--            <button class="badge badge-pill badge-warning" @click="addCTag()">C/C++</button>-->
<!--            <button class="badge badge-pill badge-success" @click="addJavaTag()">Java</button>-->
<!--            <button class="badge badge-pill badge-info" @click="addPythonTag()">Python</button>-->
          </div> <!-- .control-group -->


<!--          <div class="form-group">-->
<!--            <label for="time-limit">时间限制（ms）</label>-->
<!--            <input type="text" class="form-control" id="time-limit" placeholder="" v-model="problem.timeLimit">-->
<!--          </div>-->

<!--          <div class="form-group">-->
<!--            <label for="memory-limit">内存限制（KB）</label>-->
<!--            <input type="text" class="form-control" id="memory-limit" placeholder="" v-model="problem.memoryLimit">-->
<!--          </div>-->


<!--          <div class="btn-group">-->
<!--            <div class="row">-->
<!--              <div class="col-sm-3">-->
<!--                <file v-bind:input-id="'view-file-upload'"-->
<!--                      v-bind:text="'上传试题描述文件'"-->
<!--                      v-bind:suffixs="['jpg', 'jpeg', 'png']"-->
<!--                      v-bind:use="FILE_USE.VIEW.key"-->
<!--                      v-bind:problemId="problemId"-->
<!--                      v-bind:after-upload="afterUploadCodeFile"></file>-->
<!--              </div>-->
<!--              <div class="col-sm-3">-->
<!--                <file v-bind:input-id="'code-file-upload'"-->
<!--                      v-bind:text="'上传代码运行时读取文件'"-->
<!--                      v-bind:suffixs="['jpg', 'jpeg', 'png', 'txt', 'xlsx', 'csv']"-->
<!--                      v-bind:use="FILE_USE.READ_FILE.key"-->
<!--                      v-bind:problemId="problemId"-->
<!--                      v-bind:after-upload="afterUploadCodeFile"></file>-->
<!--              </div>-->
<!--              <div class="col-sm-2">-->
<!--                <file v-bind:input-id="'code-function-file-upload'"-->
<!--                      v-bind:text="'评测函数图形'"-->
<!--                      v-bind:suffixs="['jpg', 'jpeg', 'png', 'txt', 'xlsx']"-->
<!--                      v-bind:use="FILE_USE.EVALUATE_FUNCTION_FIGURE.key"-->
<!--                      v-bind:problemId="problemId"-->
<!--                      v-bind:after-upload="afterUploadCodeFile"></file>-->
<!--              </div>-->
<!--              <div class="col-sm-2">-->
<!--                <file v-bind:input-id="'code-geometric-file-upload'"-->
<!--                      v-bind:text="'评测几何图形'"-->
<!--                      v-bind:suffixs="['jpg', 'jpeg', 'png', 'txt', 'xlsx']"-->
<!--                      v-bind:use="FILE_USE.EVALUATE_GEOMETRIC_FIGURE.key"-->
<!--                      v-bind:problemId="problemId"-->
<!--                      v-bind:after-upload="afterUploadCodeFile"></file>-->
<!--              </div>-->
<!--              <div class="col-sm-2">-->
<!--                <file v-bind:input-id="'code-statistical-file-upload'"-->
<!--                      v-bind:text="'评测统计图形'"-->
<!--                      v-bind:suffixs="['jpg', 'jpeg', 'png', 'txt', 'xlsx']"-->
<!--                      v-bind:use="FILE_USE.EVALUATE_STATISTICAL_CHART.key"-->
<!--                      v-bind:problemId="problemId"-->
<!--                      v-bind:after-upload="afterUploadCodeFile"></file>-->
<!--              </div>-->

<!--              <div class="col-lg-2"></div>-->

<!--            </div>-->

<!--          </div>-->

          <br>

          <table id="file-table" class="table  table-bordered table-hover">


            <tbody>
            <tr v-for="(f) in files" v-bind:key="f.id">
              <td>{{f.name}}</td>
              <td>{{f.url}}</td>
              <td>{{f.size}}</td>
              <td>{{f.suffix}}</td>
              <td>{{f.use}}</td>
              <td v-if="problemId !== -1">
                <div class="hidden-sm hidden-xs btn-group">
                  <button v-on:click="deleteProblemFileById(f.id)" class="btn btn-white btn-xs btn-warning btn-round">
                    删除
                  </button>
                </div>
              </td>
            </tr>
            </tbody>
          </table>

          <form class="form-horizontal">
            <label>试题描述</label>
            <div class="form-group">
              <div class="col-lg-12">

              </div>
            </div>
            <div class="form-group">
              <div class="col-lg-12">
                <div id="content"></div>
              </div>

              <v-md-editor v-model="content"  :disabled-menus="[]"  @upload-image="handleUploadImage" height="400px"></v-md-editor>

            </div>
            <div class="form-group">
              <div class="col-lg-12">

              </div>
            </div>
          </form>


          <div class="form-group">
            <label for="hint">提示</label>
            <textarea class="form-control" id="hint" rows="3" v-model="problem.hint"></textarea>
          </div>


          <div class="form-group">
            <label for="input-format">输入格式</label>
            <textarea class="form-control" rows="5" id="input-format" v-model="problem.inputFormat"></textarea>
          </div>


          <div class="form-group">
            <label for="output-format">输出格式</label>
            <textarea class="form-control" rows="5" id="output-format" v-model="problem.outputFormat"></textarea>
          </div>


          <div class="form-group">
            <label for="input-format">输入样例</label>
            <textarea class="form-control" rows="5" id="input-sample" v-model="problem.sampleInput"></textarea>
          </div>


          <div class="form-group">
            <label for="output-format">输出样例</label>
            <textarea class="form-control" rows="5" id="output-sample" v-model="problem.sampleOutput"></textarea>
          </div>


          <div ref="form" :inline="true" :model="form" label-width="80px">

            <el-collapse accordion v-model="activeCollapseItem">
              <div v-for="(item, index) in form.testCase" :key="index">
                <el-collapse-item :name="index">
                  <template #title>
                    <label style="margin-left: 20px">测试用例{{index+1}}</label>
                    <div>
                      <el-button size="small" round type="danger" @click="deleteItem(index)" style="margin-left: 40px">
                        Delete
                      </el-button>
                    </div>
                  </template>
                  <div class="form-group" style="margin: 20px;">
                    <label>标准输入{{index + 1}}</label>
                    <textarea class="form-control" v-model="item.input" rows="3"></textarea>
                  </div>
                  <div class="form-group" style="margin: 20px;">
                    <label>标准输出{{index + 1}}</label>
                    <textarea class="form-control" v-model="item.output" rows="3"></textarea>
                  </div>
                </el-collapse-item>
              </div>
            </el-collapse>

            <div style="margin-top: 20px">
              <el-button type="success" round size="small" @click="addItem" style="margin-left: 20px">
                Add
              </el-button>
              <!--                            <el-button size="small" round type="danger" @click="deleteItem" style="margin-left: 40px">-->
              <!--                                Delete-->
              <!--                            </el-button>-->

              <el-button size="small" round type="primary" @click="expandAllTestCases" style="margin-left: 40px">
                Expand All
              </el-button>

              <el-button size="small" round type="primary" @click="collapseAllTestCases" style="margin-left: 40px">
                Collapse All
              </el-button>
            </div>

          </div>

          <br>

          <el-row>

            <el-col :span="3">

              <el-button type="success" size="large" round v-on:click="saveContent()" v-if="problemId === -1">
                保存
              </el-button>&nbsp;

              <el-button type="success" size="large" round v-on:click="editProblem()" v-if="problemId !== -1">
                编辑完成
              </el-button>&nbsp;
            </el-col>

            <el-col :span="4" v-if="problemId === -1">
              <el-button type="success" size="large" round v-on:click="toCreateProblemAgain()">
                再创建一个试题
              </el-button>&nbsp;
            </el-col>

            <el-col :span="3">
              <el-button type="success" size="large" round v-on:click="toProblemPage()" v-bind:disabled="problemId === -1">
                马上测试
              </el-button>&nbsp;
            </el-col>

            <el-col :span="3">
              <el-button type="warning" size="large" round v-on:click="cancelEdit()">
                退出编辑
              </el-button>&nbsp;
            </el-col>
          </el-row>

        </div>
      </div>
    </div>



    <el-dialog v-model="appendCategoryDialogVisible" title="新建分类" width="25%" top="30vh" center>
      <el-row>
        <el-col :span="8">
          <label>分类名称</label>
        </el-col>
        <el-col :span="8">
          <label>分类英文别名</label>
        </el-col>
        <el-col :span="8">
          <label>展示顺序</label>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-input v-model="problemCategoryName"></el-input>
        </el-col>
        <el-col :span="8">
          <el-input v-model="problemCategorySlug"></el-input>
        </el-col>
        <el-col :span="8">
          <el-input v-model="showPriority"></el-input>
        </el-col>

      </el-row>
      <template #footer>
              <span class="dialog-footer">
                <el-button @click="appendCategoryDialogVisible = false">Cancel</el-button>
                <el-button color="#626aef" @click="saveCategoryChanges">
                    Save
                </el-button>
              </span>
      </template>
    </el-dialog>


    <el-dialog
        title="提示"
        v-model="dialogLanguage"
        width="30%"
        :before-close="handleClose">

      <div class="form-group">
        <label for="time-limit">时间限制（ms）</label>
        <input type="text" class="form-control" id="time-limit" placeholder="" v-model="timeLimit">
      </div>

      <div class="form-group">
        <label for="memory-limit">内存限制（KB）</label>
        <input type="text" class="form-control" id="memory-limit" placeholder="" v-model="memoryLimit">
      </div>
<!--      <el-button @click="cancelLanguage()">取 消</el-button>-->
      <el-button type="primary" @click="submitLanguage()">确 定</el-button>

    </el-dialog>

    <el-dialog v-model="categoryDialogVisible" title="试题分类管理" width="50%" top="20vh" center>
      <perfect-scrollbar style="height: 50vh">
        <el-tree
            :data="elTreeDataSource"
            node-key="id"
            :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <span>{{ node.label }}</span>
                      <span>
                        <el-button size="small" type="warning" round @click="editCategory(data)">
                            Edit
                        </el-button>
                        <el-button size="small" type="success" round @click="append(data)" v-bind:disabled="data.parentId !== 0">
                            Append
                        </el-button>


                          <el-popconfirm
                              confirm-button-text="Yes"
                              cancel-button-text="Cancel"
                              icon-color="#626AEF"
                              title="Are you sure to delete this?"
                              @confirm="remove(node, data)"
                          >
                            <template #reference>
                                <el-button style="margin-left: 8px" size="small" color="red" round>
                                    Delete
                                </el-button>
                            </template>
                          </el-popconfirm>
                      </span>
                    </span>
          </template>
        </el-tree>
      </perfect-scrollbar>

      <template #footer>
              <span class="dialog-footer">
                <el-button @click="categoryDialogVisible = false">Cancel</el-button>
                <el-button color="#626aef" @click="appendMainCategory">
                    Add Main Category
                </el-button>
              </span>
      </template>
    </el-dialog>

  </main>
</template>

<script>
import File from "./file.vue"
import API from '../api/trainer/questionManager'
import APIBASE from '../api/base/upload'

import axios from "axios";
export default {
  name: "createProblem",
  components: {File},
  data() {
    return {
      activeCollapseItem: 0,
      problem: {},
      languageList:[],
      companyList:[],
      dialogLanguage:false,
      C:false,
      CPlus:false,
      JAVA:false,
      PASCAL:false,
      PYTHON:false,
      RUBY:false,
      languageId:0,
      memoryLimit:0,
      timeLimit:0,
      categoryOptions: "",
      currentNodeData: "",
      problemCategoryName: "",
      problemCategorySlug: "",
      parentProblemCategory: "",
      showPriority: 100,
      level1: [],
      level2: [],
      elTreeDataSource: [],
      foldSwitchStatus:false,
      problemId: -1,
      saveProblemId:-1,  //第一次保存题目不传，保存后得到题目id
      files: [],
      problemDescriptionFile: [],
      problemCategories: [{
        parentCategory: '',
        categoryLevelTwo: []
      }
      ],
      activeItem: [],
      problemCategoryMap: new Map(),
      selectedCategory: '',
      form: {
        testCase: [
          {
            input: "",
            output: "",
          }
        ]
      },
      content: "",
      company:'',
      categorys: "",
      newCategory: "",
      categoryDialogVisible: false,
      appendCategoryDialogVisible: false,
      FILE_USE: FILE_USE,
      FILE_DOMAIN: FILE_DOMAIN,

    }


  },

  mounted() {
    let _this = this;
    _this.initPage();
    _this.getProblemCategory();
    _this.allCategory();
    _this.allCompany();
  },
  methods: {

    initPage() {
      Loading.show();
      this.problem = LocalStorage.get(CURRENT_EDIT_PROBLEM);
      //如果传入problem参数则是编辑页面
      if(this.problem != undefined) {
        this.problemId = this.problem.problemId;
        this.company = this.problem.companyName

        this.problem.exactlyMatch = this.problem.exactlyMatch ? 'Yes' : 'No';
        this.content = this.problem.description;
        this.activeItem = this.problem.problemCategorySlugs.split(",");
        this.selectedCategory = this.problem.problemCategories;
        this.getLanguageList(this.problem.languageList)
        this.getProblemFileByProblemId();
        this.getProblemCheckPointByProblemId(this.problem.testcase);

      }
      else {
        this.problem = {};
      }
      Loading.hide();
    },

    editCategory(data) {
      this.problemCategoryId = data.id;
      this.problemCategoryName = data.label;
      this.problemCategorySlug = data.alias;
      this.parentProblemCategory = data.parentId;
      this.showPriority = data.showPriority;
      this.categoryOptions = "Edit";
      this.appendCategoryDialogVisible = true;
    },

    appendMainCategory() {
      this.categoryOptions = "AppendMain";
      this.appendCategoryDialogVisible = true;

    },

    append(data) {
      this.currentNodeData = data;
      this.categoryOptions = "AppendSub";
      this.problemCategoryName = "";
      this.problemCategorySlug = "";
      this.appendCategoryDialogVisible = true;
    },

    saveCategoryChanges() {
      let _this = this;
      if(!Number.isFinite(_this.showPriority)) {
        _this.$notify.warning("Show Priority Require Number...");
        return;
      }
      switch (_this.categoryOptions) {
        case "Edit":
          _this.$axios.post('/training/editProblemCategory', {
            problemCategoryId    : _this.problemCategoryId,
            problemCategorySlug  : _this.problemCategorySlug,
            problemCategoryName  : _this.problemCategoryName,
            parentProblemCategory: _this.parentProblemCategory,
            showPriority: _this.showPriority,
          }).then((res) => {
            if(res.data.success) {
              _this.$notify.success("Success...");
              _this.allCategory();
            }
          }).catch((err) => {
            console.log(err);
          });
          break;
        case "AppendMain":
          _this.$axios.post('/training/createProblemCategory', {
            problemCategorySlug  : _this.problemCategorySlug,
            problemCategoryName  : _this.problemCategoryName,
            parentProblemCategory: "",
          }).then((res) => {
            if(res.data.success) {
              _this.$notify.success("Success...");
              _this.allCategory();
            }
          }).catch((err) => {
            console.log(err);
          });
          break;
        case "AppendSub":
          console.log(_this.currentNodeData)
          _this.$axios.post('/training/createProblemCategory', {
            problemCategorySlug  : _this.problemCategorySlug,
            problemCategoryName  : _this.problemCategoryName,
            showPriority: _this.showPriority,
            parentProblemCategory: this.currentNodeData.label,
          }).then((res) => {
            if(res.data.success) {
              _this.$notify.success("Success...");
              _this.allCategory();
            }
          }).catch((err) => {
            console.log(err);
          });
          break;
        default:
          break;
      }
      console.log(_this.elTreeDataSource);
      _this.appendCategoryDialogVisible = false;
    },

    remove(node, data){
      let _this = this;
      _this.$axios.post('/training/deleteProblemCategories', {
        problemCategoryId    : data.id,
      }).then((res) => {
        if(res.data.success) {
          _this.$notify.success("Success...");
          _this.allCategory();
        }
      }).catch((err) => {
        console.log(err);
      });

      console.log(_this.elTreeDataSource);
    },
    /**
     * 所有公司查询
     */

    allCompany(){
      let token = localStorage.getItem('token')
      API.getCompany(token).then(res=>{
        this.companyList = res.data.content
        console.log(this.companyList)
      }).catch(e=>{
        console.log(e)
      })
    },
    /**
     * 所有分类查询
     */
    allCategory() {

      let _this = this;
      let token = localStorage.getItem('token')

      API.questionCategoryList(token).then((res) => {
        console.log(res.data)
        if(res.data.success) {
          _this.categorys = res.data.content;
          // 将所有记录格式化成树形结构
          _this.level1 = [];
          for (let i = 0; i < _this.categorys.length; i++) {
            let c = _this.categorys[i];
            _this.problemCategoryMap.set(c.problemCategorySlug.toString(), c.problemCategoryName);
            if (c.problemCategoryParentId === 0) {
              _this.level1.push(c);
            } else {
              _this.level2.push(c);
            }
          }
          console.log(this.level1)
          _this.elTreeDataSource = []
          for (let i = 0; i < _this.level1.length; i++) {
            let elTreeParentData = {
              id: _this.level1[i].problemCategoryId,
              label: _this.level1[i].problemCategoryName,
              alias: _this.level1[i].problemCategorySlug,
              showPriority: _this.level1[i].showPriority,
              parentId: _this.level1[i].parentProblemCategoryId,
              children: [],
            }
            for (let j = 0; j < _this.level2.length; j++) {
              if (_this.level2[j].problemCategoryParentId === _this.level1[i].problemCategoryId) {
                let elTreeChildrenData = {
                  id: _this.level2[j].problemCategoryId,
                  label: _this.level2[j].problemCategoryName,
                  alias: _this.level2[j].problemCategorySlug,
                  showPriority: _this.level2[j].showPriority,
                  parentId: _this.level2[j].problemCategoryParentId,
                }
                elTreeParentData.children.push(elTreeChildrenData);
              }
            }
            _this.elTreeDataSource.push(elTreeParentData);
          }
          console.log(54)
          console.log(this.elTreeDataSource)
        }
      }).catch((err) => {
        console.log(err);
      });


    },
    getLanguageList(languageList){

      languageList.forEach(e=>{
        if(e.languageName==='C') {
          this.C = true
          let param = {}
          param.languageId  = 1
          param.memoryLimit = e.memoryLimit
          param.timeLimit = e.timeLimit
          this.languageList.push(param)
        }else if(e.languageName==='C_PLUS_PLUS'){
          this.CPlus = true
          let param = {}
          param.languageId  = 2
          param.memoryLimit = e.memoryLimit
          param.timeLimit = e.timeLimit
          this.languageList.push(param)

        }else if(e.languageName==='RUBY'){
          this.RUBY = true
          let param = {}
          param.languageId  = 6
          param.memoryLimit = e.memoryLimit
          param.timeLimit = e.timeLimit
          this.languageList.push(param)
        }else if(e.languageName==='PYTHON'){
          this.PYTHON = true
          let param = {}
          param.languageId  = 5
          param.memoryLimit = e.memoryLimit
          param.timeLimit = e.timeLimit
          this.languageList.push(param)
        }else if(e.languageName==='JAVA'){
          this.JAVA = true
          let param = {}
          param.languageId  = 3
          param.memoryLimit = e.memoryLimit
          param.timeLimit = e.timeLimit
          this.languageList.push(param)
        }else if(e.languageName==='PASCAL'){
          this.PASCAL = true
          let param = {}
          param.languageId  = 4
          param.memoryLimit = e.memoryLimit
          param.timeLimit = e.timeLimit
          this.languageList.push(param)
        }
      })
    },
    getProblemFileByProblemId() {

      // let _this = this;
      // _this.$axios.post('/training/getProblemFileByProblemId', {
      //   problemId: _this.problem.problemId,
      // }).then((res) => {
      //   if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
      //     this.$router.go(0);
      //     return;
      //   }
      //   if (res.data) {
      //     _this.files = res.data;
      //     for (let i = 0; i < _this.files.length; i++) {
      //       _this.files[i].url = FILE_DOMAIN + _this.files[i].path;
      //     }
      //     console.log(FILE_DOMAIN)
      //   }
      // }).catch((err) => {
      //   this.$notify.error("请求失败，请联系管理员");
      //   console.log(err);
      // });
    },

    getProblemCheckPointByProblemId(testcase) {
      console.log(testcase)
      this.form.testCase = []
      testcase.forEach(e=>{
        let test = {}
        test.input = e.checkpointInput
        test.output = e.checkpointOutput
        this.form.testCase.push(test)
      })
      // let _this = this;
      // _this.$axios.post('/training/getProblemCheckPointByProblemId',
      //     {
      //       problemId: _this.problem.problemId,
      //     }).then((res) => {
      //   if (res.data === 'Unauthorized'  || res.data === 'Forbidden') {
      //     this.$router.go(0);
      //     return;
      //   }
      //
      //   if (res.data) {
      //     if(res.data.length !== 0) {
      //       _this.form.testCase = res.data
      //     }
      //   }
      //
      // }).catch((err) => {
      //   this.$notify.error("请求失败，请联系管理员");
      //   console.log(err);
      // });
    },

    editProblem() {
      let _this = this;
      let problemName = $('#problem-name').val(),
          // timeLimit = $('#time-limit').val(),
          // memoryLimit = $('#memory-limit').val(),
          description = _this.content,
          hint = $('#hint').val(),
          inputFormat = $('#input-format').val(),
          outputFormat = $('#output-format').val(),
          inputSample = $('#input-sample').val(),
          outputSample = $('#output-sample').val(),
          testCases = JSON.stringify(_this.form.testCase),
          problemCategories = JSON.stringify(_this.activeItem),
          isPublic = $("#problem-is-public").val() === "公开" ? true : false,
          isExactlyMatch = $("#problem-is-exactly-match").val() === "Yes" ? true : false,
          problemTags = JSON.stringify([$('#problem-tag').val()]);
      let companyId = 0
      _this.companyList.forEach(e=>{
        if(e.name===$('#problem-company').val()){
          companyId =e.id
        }
      })

      if (!Validator.require(outputSample, 'outputSample') &&
          !Validator.require(inputSample, 'inputSample') &&
          !Validator.require(outputFormat, 'outputFormat') &&
          !Validator.require(inputFormat, 'inputFormat') &&
          !Validator.require(description, 'description') &&
          !Validator.require(problemName, 'problemName')) {
        return;
      }
      Loading.show();

      let token = localStorage.getItem('token')
      let param = {}
      // if(this.saveProblemId!==-1){
      //   param.problemId = this.saveProblemId
      // }
      param.problemId = this.problemId
      param.problemName = problemName
      param.languageList = this.languageList

      param.problemDescription = description
      param.problemHint = hint
      param.problemInputFormat =inputFormat
      param.problemOutputFormat = outputFormat
      param.problemSampleInput = inputSample
      param.problemSampleOutput = outputSample
      param.testCases = testCases
      param.problemCategories = problemCategories
      param.problemTags =problemTags
      param.problemIsPublic = isPublic
      param.isExactlyMatch = isExactlyMatch
      if(companyId!==0) {
        param.companyId = companyId
      }
      API.questionSave(param,token).then((res) => {
        Loading.hide();
        if (res.data === 'Unauthorized'  || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data.success) {
          this.saveProblemId = res.data.content
          console.log(param)
          this.$message({
            message:'创建成功！',
            type:"success"
          })
        }

      }).catch((err) => {
        Loading.hide();
        _this.$notify.error("提交失败，请联系管理员");
        console.log(err);
      });


      // let _this = this;
      //
      // let problemName         = _this.problem.problemName,
      //     timeLimit           = _this.problem.timeLimit   ,
      //     memoryLimit         = _this.problem.memoryLimit ,
      //     description         = _this.content ,
      //     hint                = _this.problem.hint        ,
      //     inputFormat         = _this.problem.inputFormat ,
      //     outputFormat        = _this.problem.outputFormat,
      //     inputSample         = _this.problem.sampleInput ,
      //     outputSample        = _this.problem.sampleOutput,
      //     testCases           = JSON.stringify(_this.form.testCase),
      //     problemCategories   = JSON.stringify(_this.activeItem),
      //     isPublic            = _this.problem.isPublic === "公开" ? true : false,
      //     isExactlyMatch      = _this.problem.isExactlyMatch === "Yes" ? true : false,
      //     problemTags         = JSON.stringify([$('#problem-tag').val()]);
      //
      //
      // if (!Validator.require(outputSample, 'outputSample') &&
      //     !Validator.require(inputSample, 'inputSample') &&
      //     !Validator.require(outputFormat, 'outputFormat') &&
      //     !Validator.require(inputFormat, 'inputFormat')&&
      //     !Validator.require(description, 'description') &&
      //     !Validator.require(problemName, 'problemName')) {
      //   return;
      // }
      //
      // Loading.show();
      //
      // let problemId = _this.problem.problemId;
      //
      // _this.$axios.post('/training/editProblem',
      //     {
      //       problemName:          problemName,
      //       problemId:            problemId,
      //       timeLimit:            timeLimit,
      //       memoryLimit:          memoryLimit,
      //       description:          description,
      //       hint:                 hint,
      //       inputFormat:          inputFormat,
      //       outputFormat:         outputFormat,
      //       inputSample:          inputSample,
      //       outputSample:         outputSample,
      //       testCases:            testCases,
      //       problemCategories:    problemCategories,
      //       problemTags:          problemTags,
      //       isPublic:             isPublic,
      //       isExactlyMatch:       isExactlyMatch
      //     }).then((res) => {
      //   Loading.hide();
      //   if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
      //     _this.$router.push({path: '/home'});
      //     return;
      //   }
      //
      //   if (res.data.isSuccessful) {
      //     _this.problem.description = _this.content;
      //     LocalStorage.set(CURRENT_PROBLEM, _this.problem);
      //     _this.$notify.success("Save Problem Successfully...");
      //   }
      //   else {
      //     Toast.error("Save Problem failed...")
      //   }
      //
      // }).catch((err) => {
      //   this.$notify.error("提交失败，请联系管理员");
      //   console.log(err);
      // });

    },

    toCreateProblemAgain() {
      this.problemId = -1;
      this.$router.go(0);
    },

    toProblemPage() {
      if(this.problemId === -1) {
        return;
      }
      LocalStorage.set(CURRENT_PROBLEM, this.problem);
      let routeUrl = this.$router.resolve({
        path: "/list/problem",
      });
      window.open(routeUrl.href, '_blank');
    },

    cancelEdit() {
      localStorage.removeItem('CURRENT_EDIT_PROBLEM')
      this.$router.push({path: "/public/questionList"});
      // this.$router.back()
    },

    findNextBracket(problemDescriptionFileContent, index) {
      let findIndex = index;
      for (let i = index + 2; i < problemDescriptionFileContent.length; i++) {
        if(problemDescriptionFileContent.charAt(i) === '【') {
          return i;
        }
      }
      return findIndex;
    },
    problemDescriptionFileContentParse(problemDescriptionFileContent) {
      let _this = this;
      let problemName     = "";
      let timeLimit       = "";
      let memoryLimit     = "";
      let description     = "";
      let hint            = "";
      let inputFormat     = "";
      let outputFormat    = "";
      let inputSample     = "";
      let outputSample    = "";
      let testCases       = "";

      let tagNames = [
        "【标题】",
        "【时间限制】",
        "【内存限制】",
        "【题目描述】",
        "【提示】",
        "【输入格式】",
        "【输出格式】",
        "【输入样例】",
        "【输出样例】"
      ]

      let tags = [
        problemName,
        timeLimit,
        memoryLimit,
        description,
        hint,
        inputFormat,
        outputFormat,
        inputSample,
        outputSample,
      ]

      for(let i = 0; i < tags.length; i++) {
        let tagIndex = problemDescriptionFileContent.indexOf(tagNames[i]);
        let tagNameLength = tagNames[i].length;
        let startIndex = tagIndex + tagNameLength + 2;
        let endIndex = this.findNextBracket(problemDescriptionFileContent, tagIndex) - 2;
        tagIndex == -1 ? tags[i] = "" : tags[i] = problemDescriptionFileContent.substring(startIndex, endIndex);
        console.log(tags[i])
      }

      this.form.testCase = [];
      let testCasesStartIndex = problemDescriptionFileContent.indexOf("【测试集】");
      testCases = problemDescriptionFileContent.substring(testCasesStartIndex + 7);
      for (let i = 1; i <= 10; i++) {
        let testCase = "";

        let flagStartTagName = "【测试点 " + i + "】";
        let flagEndTagName = "【测试点 " + (i+1) + "】";
        let flagStartTagNameIndex = testCases.indexOf(flagStartTagName);
        let flagEndTagNameIndex = testCases.indexOf(flagEndTagName);
        if(flagEndTagNameIndex == -1) {
          flagEndTagNameIndex = testCases.indexOf("【标准例程】");
          if(flagEndTagNameIndex == -1) {
            break;
          }
        }
        if(flagStartTagNameIndex == -1 || testCasesStartIndex == -1) {
          break;
        }
        let startIndex = flagStartTagNameIndex+ flagStartTagName.length + 2;
        let endIndex = flagEndTagNameIndex - 2;
        testCase = testCases.substring(startIndex, endIndex);
        let input = testCase.substring(testCase.indexOf("【输入】") + 6, testCase.indexOf("【输出】") - 2);
        let output = testCase.substring(testCase.indexOf("【输出】") + 6, this.findNextBracket(problemDescriptionFileContent, testCase.indexOf("【输出】") + 6));
        this.form.testCase.push(
            {
              input: input,
              output: output,
            }
        )
      }
      _this.problem.problemName = tags[0];
      _this.problem.timeLimit =   tags[1];
      _this.problem.memoryLimit = tags[2];
      _this.content             = tags[3];
      _this.problem.hint        = tags[4];
      _this.problem.inputFormat = tags[5];
      _this.problem.outputFormat = tags[6];
      _this.problem.sampleInput = tags[7];
      _this.problem.sampleOutput = tags[8];

    },

    //解析试题描述文件的内容，并填充到创建试题编辑框中
    problemDescriptionFileParse(param) {
      let _this = this;
      let fileObj = param.file; // 相当于input里取得的files
      let fReader = new FileReader();
      fReader.readAsText(fileObj, "UTF-8");
      fReader.onload = evt => {

        var problemDescriptionFileContent = evt.target.result.toString();

        _this.problemDescriptionFileContentParse(problemDescriptionFileContent);
      };
    },

    /**
     * 上传内容文件后，保存内容文件记录
     */
    afterUploadCodeFile(response) {
      let _this = this;
      console.log("开始保存文件记录");

      console.log(response);
      let file = response.content;
      file.url = FILE_DOMAIN + file.path;
      _this.files.push(file);
    },

    saveContent() {

      let _this = this;
      let problemName = $('#problem-name').val(),
          // timeLimit = $('#time-limit').val(),
          // memoryLimit = $('#memory-limit').val(),
          description = _this.content,
          hint = $('#hint').val(),
          inputFormat = $('#input-format').val(),
          outputFormat = $('#output-format').val(),
          inputSample = $('#input-sample').val(),
          outputSample = $('#output-sample').val(),
          testCases = JSON.stringify(_this.form.testCase),
          problemCategories = JSON.stringify(_this.activeItem),
          isPublic = $("#problem-is-public").val() === "公开" ? true : false,
          isExactlyMatch = $("#problem-is-exactly-match").val() === "Yes" ? true : false,
          problemTags = JSON.stringify([$('#problem-tag').val()]);
          let companyId = 0
          _this.companyList.forEach(e=>{
            if(e.name===$('#problem-company').val()){
              companyId =e.id
            }
          })

      if (!Validator.require(outputSample, 'outputSample') &&
          !Validator.require(inputSample, 'inputSample') &&
          !Validator.require(outputFormat, 'outputFormat') &&
          !Validator.require(inputFormat, 'inputFormat') &&
          !Validator.require(description, 'description') &&
          !Validator.require(problemName, 'problemName')) {
        return;
      }
      Loading.show();

      let token = localStorage.getItem('token')
      let param = {}
      if(this.saveProblemId!==-1){
        param.problemId = this.saveProblemId
      }
      param.problemName = problemName
      param.languageList = this.languageList

      param.problemDescription = description
      param.problemHint = hint
      param.problemInputFormat =inputFormat
      param.problemOutputFormat = outputFormat
      param.problemSampleInput = inputSample
      param.problemSampleOutput = outputSample
      param.testCases = testCases
      param.problemCategories = problemCategories
      param.problemTags =problemTags
      param.problemIsPublic = isPublic
      param.isExactlyMatch = isExactlyMatch
      if(companyId!==0) {
        param.companyId = companyId
      }
      API.questionSave(param,token).then((res) => {
        Loading.hide();
        if (res.data === 'Unauthorized'  || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data.success) {
          this.saveProblemId = res.data.content
          console.log(param)
          this.$message({
            message:'创建成功！',
            type:"success"
          })
        }

      }).catch((err) => {
        Loading.hide();
        _this.$notify.error("提交失败，请联系管理员");
        console.log(err);
      });

      // axios.post( '/training/createProblem',{
      //   problemName: problemName,
      //   timeLimit: timeLimit,
      //   memoryLimit: memoryLimit,
      //   description: description,
      //   hint: hint,
      //   inputFormat: inputFormat,
      //   outputFormat: outputFormat,
      //   inputSample: inputSample,
      //   outputSample: outputSample,
      //   testCases: testCases,
      //   problemCategories: problemCategories,
      //   problemTags: problemTags,
      //   isPublic: isPublic,
      //   isExactlyMatch: isExactlyMatch,
      //   problemFiles: JSON.stringify(_this.files)
      // }).then((res) => {
      //   Loading.hide();
      //   if (res.data === 'Unauthorized'  || res.data === 'Forbidden') {
      //     _this.$router.push({path: '/home'});
      //     return;
      //   }
      //
      //   if (res.data.isSuccessful) {
      //     _this.$notify.success("Create Problem Successfully, Problem Id Is " + res.data.problemId);
      //     _this.problemId = res.data.problemId;
      //     _this.problem = res.data.currentProblem;
      //     _this.problem.problemTags = $('#problem-tag').val();
      //     isPublic ? _this.problem.isPublic = "公开" : _this.problem.isPublic = "私有";
      //     isExactlyMatch ? _this.problem.isExactlyMatch = "Yes" : _this.problem.isExactlyMatch = "No";
      //     isExactlyMatch ? _this.problem.exactlyMatch = "Yes" : _this.problem.exactlyMatch = "No";
      //     _this.problem.problemCategories = _this.selectedCategory;
      //     _this.problem.problemCategorySlugs = _this.activeItem.join(",");
      //     LocalStorage.set(CURRENT_EDIT_PROBLEM, _this.problem);
      //   }
      //   else {
      //     var isDescriptionEmpty  = !res.data.isDescriptionEmpty      ?   "" : "Description Is Empty... ";
      //     var isInputFormatEmpty  = !res.data.isInputFormatEmpty      ?   "" : "InputFormat Is Empty... ";
      //     var isInputSampleEmpty  = !res.data.isInputSampleEmpty      ?   "" : "InputSample Is Empty... ";
      //     var isMemoryLimitLegal  = res.data.isMemoryLimitLegal       ?   "" : "MemoryLimit Is Not Legal... ";
      //     var isOutputFormatEmpty = !res.data.isOutputFormatEmpty     ?   "" : "OutputFormat Is Empty... ";
      //     var isOutputSampleEmpty = !res.data.isOutputSampleEmpty     ?   "" : "OutputSample Is Empty... ";
      //     var isProblemNameEmpty  = !res.data.isProblemNameEmpty      ?   "" : "ProblemName Is Empty...  ";
      //     var isProblemNameLegal  = res.data.isProblemNameLegal       ?   "" : "Problem Name Is Not Legal... ";
      //     var isTimeLimitLegal    = res.data.isTimeLimitLegal         ?   "" : "TimeLimit Is Not Legal... ";
      //     let errorMessage = isDescriptionEmpty  +
      //         isInputFormatEmpty +
      //         isInputSampleEmpty +
      //         isMemoryLimitLegal +
      //         isOutputFormatEmpty +
      //         isOutputSampleEmpty +
      //         isProblemNameEmpty +
      //         isProblemNameLegal +
      //         isTimeLimitLegal;
      //     _this.$notify.error(errorMessage);
      //   }
      //
      // }).catch((err) => {
      //   Loading.hide();
      //   _this.$notify.error("提交失败，请联系管理员");
      //   console.log(err);
      // });

    },

    onCheck(name) {
      let _this = this;
      //点击子目录
      // if(parentName !== "") {
      //   if(!_this.activeItem.includes(parentName) && !_this.activeItem.includes(name)) {
      //     _this.activeItem.push(parentName);
      //   }
      // }
      if (_this.activeItem.includes(name)) {
        _this.removeObj(_this.activeItem, name);
      } else {
        _this.activeItem.push(name);
      }
      //显示选中的试题分类
      let categoryList = []
      for (let i = 0; i < this.activeItem.length; i++) {
        let currentKey = this.activeItem[i].toString();
        let currentCategoryName = this.problemCategoryMap.get(currentKey);
        categoryList.push(currentCategoryName);
      }
      this.selectedCategory = categoryList.join(",");
    },


    /**
     * 移除对象数组中的对象
     * @param array
     * @param obj
     * @returns {number}
     */
    removeObj(array, obj) {
      let index = -1;
      for (let i = 0; i < array.length; i++) {
        if (array[i] === obj) {
          array.splice(i, 1);
          index = i;
          break;
        }
      }
      return index;
    },

    addLanguage(language,languageId){
      this.languageId = languageId
      if(language) {
        this.dialogLanguage = true
      }else{
        for (let i = 0; i < this.languageList.length; i++) {
          if(languageId===this.languageList[i].languageId){
            console.log(i)
            this.languageList.splice(i,1)
          }
        }
      }
      console.log(this.languageList)
    },
    cancelLanguage(){
      this.dialogLanguage = false
    },
    submitLanguage(){
      let param = {}
      param.languageId = this.languageId
      param.timeLimit = this.timeLimit
      param.memoryLimit = this.memoryLimit
      this.languageList.push(param)

      this.dialogLanguage = false
    },

    addCTag() {
      let problemName = $('#problem-name').val();
      let start = problemName.indexOf("【");
      let end = problemName.indexOf("】");
      let languageTagNames = problemName.substring(start + 1, end);
      if (languageTagNames.length == 0 || start == -1) {
        languageTagNames = "【" + "C/C++" + "】"
        problemName = problemName + " " + languageTagNames;
      } else if (languageTagNames.indexOf("C/C++") == -1) {
        languageTagNames = "【" + languageTagNames + "/C/C++" + "】";
        problemName = problemName.replace(/【.*】/, languageTagNames);
      }
      $('#problem-name').val(problemName);
      this.problem.problemName = problemName
    },

    addJavaTag() {
      let problemName = $('#problem-name').val();
      let start = problemName.indexOf("【");
      let end = problemName.indexOf("】");
      let languageTagNames = problemName.substring(start + 1, end);
      if (languageTagNames.length == 0 || start == -1) {
        languageTagNames = "【" + "Java" + "】"
        problemName = problemName + " " + languageTagNames;
      } else if (languageTagNames.indexOf("Java") == -1) {
        languageTagNames = "【" + languageTagNames + "/Java" + "】";
        problemName = problemName.replace(/【.*】/, languageTagNames);
      }
      $('#problem-name').val(problemName);
      this.problem.problemName = problemName
    },

    addPythonTag() {
      let problemName = $('#problem-name').val();
      let start = problemName.indexOf("【");
      let end = problemName.indexOf("】");
      let languageTagNames = problemName.substring(start + 1, end);
      if (languageTagNames.length == 0 || start == -1) {
        languageTagNames = "【" + "Python" + "】"
        problemName = problemName + " " + languageTagNames;
      } else if (languageTagNames.indexOf("Python") == -1) {
        languageTagNames = "【" + languageTagNames + "/Python" + "】";
        problemName = problemName.replace(/【.*】/, languageTagNames);
      }
      $('#problem-name').val(problemName);
      this.problem.problemName = problemName
    },

    addItem() {
      this.form.testCase.push({
        input: "",
        output: ""
      });
      this.activeCollapseItem = this.form.testCase.length - 1
      console.log(this.activeCollapseItem)
    },


    deleteItem(index) {
      this.form.testCase.splice(index, 1);
      console.log(this.form.testCase, "删除");
    },

    expandAllTestCases() {
      this.activeCollapseItem = []
      for (let i = 0; i < this.form.testCase.length; i++) {
        this.activeCollapseItem.push(i)
      }
    },

    collapseAllTestCases() {
      this.activeCollapseItem = -1
    },

    getProblemCategory() {
      let _this = this;
      let token = localStorage.getItem('token')
      API.questionCategoryList(token).then((res) => {
        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }

        if (res.data) {
          _this.problemCategories = res.data.content;

        }

      }).catch((err) => {
        this.$notify.error("提交失败，请联系管理员");
        console.log(err);
      });
    },

    deleteProblemFileById(id) {
      let _this = this;
      Loading.show();
      _this.$axios.post('/training/deleteProblemFileById',
          {
            id: id
          }).then((res) => {
        Loading.hide()
        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }
        if (res.data.success) {
          _this.getProblemFileByProblemId();
          _this.$notify("Delete Problem Associated File Successfully...");
        }
        else {
          _this.$notify("Delete Problem Associated File Failed...");
        }

      }).catch((err) => {
        this.$notify.error("提交失败，请联系管理员");
        console.log(err);
        Loading.hide()
      });
    },
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      // console.log(files);
      let  param = {}
      let token = localStorage.getItem('token')
      console.log(files[0])

      let data = new FormData()
      data.append('file', files[0])// 传文件
      data.append('use','V')
      // param.file =files[0]
      // param.use = 'V'
      APIBASE.uploadImage(param,token).then(res=>{
        console.log(res)
      }).catch(e=>{
        console.log(e)
      })
      // console.log(param)
      // 此处只做示例
      insertImage({
        url:
            'https://tse1-mm.cn.bing.net/th/id/OIP-C.k6cV-xPHiXv7vH3FL2F_dQHaE8?rs=1&pid=ImgDetMain',
        desc: '七龙珠',
        // width: 'auto',
        // height: 'auto',
      });
    },


  }
}
</script>

<style scoped>

label {
  font-weight: bold;
}

th {
  font-weight: normal;
}

.active {
  float: left;
  margin-left: 10px;
  padding: 10px;
  background: #efc531;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.Classification {
  float: left;
  margin-left: 10px;
  padding: 10px;
  background:#e9ecef;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.upload-box {
  height: 120px;
  margin: 0 2% 20px;
  font-weight: 100;
  border: 2px #bbb dashed;
  border-radius: 8px;
  display: flex;
  align-items: center;
}

.upload-content {
  margin: 0 auto;
}

.upload-content .file-upload {
  display: inline-block;
  margin-left: 1rem;
}

.upload-content span {
  font-size: 1.5rem;
  color: darkgrey;
}

.upload-tip a {
  text-decoration: none;
  color: #409EFF;
}

.upload-tip {
  margin-top: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>